/**
 * Created by Administrator on 2017-7-27.
 */
import nattyStorage from 'natty-storage';
import Utils from '../utils'
import DB from './db';

const storage = nattyStorage({
  type: 'localStorage',  // 缓存方式, 默认为'localStorage'
  key: 'sskj-wechat',     // !!! 唯一必选的参数, 用于内部存储 !!!
  tag: 'v1.0.0.0',          // 缓存的标记, 用于判断是否有效
  duration: 1000 * 60 * 5,      // 缓存的有效期长, 以毫秒数指定
});

let StorageUtils = {

  getStorage(){
    return storage;
  },

  getStorageItem(key) {
    return storage.get(key);
  },

  removeStorageItem(key) {
    storage.remove(key);
  },

  setStorage(key, value) {
    storage.set(key, value);
  },

  deleUserInfo(){
    storage.remove('user');
  },

  createUser(){
    // storage.remove('user');
    // if (!storage.get('user')) {
    //   storage.set('user', {id:'xxx',name:'游客',openId:'xxx',phone:'xxxxxxxxxxx',doors:[],courts:[],state:'正常',priType:'游客'});
    // }
  },

  upUser(o){
    if (storage.get('user')) {
      storage.set('user', {id:o.id,name:o.name,phone:o.phone,state:o.state});
    }
  },

  updateUser(o) {
    let user = storage.get('user');
    if (user) {
      storage.set('user', {
        ...user,
        ...o
      })
    }
  },

  getUser(){
    return storage.get('user');
  },

  getUserInfo(resolve, reject){
    const code = Utils.GetQueryString(window.location.search, 'code');
    DB.WechatAPI.getUser({code: code}).then(
      function (content) {
        storage.set('user', content);
        resolve(JSON.stringify(content));
      },
      function (error) {
        reject(JSON.stringify(error));
      }
    ).catch(function (reason) {
      alert("系统错误");
    });
  }
};

export default StorageUtils;
